<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    chartTitle: {
      type: String,
      default: '累计'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
      // console.log(this.chartData)
    },
    setOptions(chartData) {
      this.chart.setOption({
        title: {
          text: '日期统计',
          textStyle: {
            color: '#ec7644',
            fontSize: 14
          },
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        // legend: {
        //   data: [this.chartTitle]
        // },
        grid: {
          left: 20,
          right: 30,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: chartData.date,
          axisLabel: {
            rotate: 60
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          type: 'line',
          name: this.chartTitle,
          smooth: true,
          areaStyle: {},
          data: chartData.value,
          itemStyle: {
            color: '#ec7644'
          },
          animationDuration: 2000,
          animationEasing: 'cubicInOut'
        }]
      })
    }
  }
}
</script>
